package cn.agiledata.bank.barcodepayment.logic;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import cn.agiledata.bank.barcodepayment.exception.BarCodePayException;
import cn.agiledata.bank.common.util.DateUtil;

/**
 * 涓婃捣鐢靛姏鍏徃鐢佃垂鏉″舰鐮�
 * 
 * @author 马贤波
 * 
 */
public class SmepcBarCode extends AbstractBarCode {
    /**
     * 鏉″舰鐮佸�鐨勯暱搴�
     */
    private static final int CODE_SIZE = 24;

    public BigDecimal getAmount() {
        return getAmount(16, 23);
    }

    protected void validate(String barCodeValue) throws BarCodePayException {
        super.validate(barCodeValue);

        if (barCodeValue.length() != CODE_SIZE) {
            throw BarCodePayException.ERROR_BARCODE_LENGTH;
        }
        int sum = 0;
        for (int i = 1; i <= barCodeValue.length(); i++) {
            if (i % 2 == 1) { // 濂囨暟浣�
                sum += intOf(barCodeValue, i) * 3;
            } else { // 鍋舵暟浣�
                sum += intOf(barCodeValue, i);
            }
        }
        if (sum % 10 != 0) { // 涓綅鏁颁笉涓�
            throw BarCodePayException.ERROR_BARCODE;
        }
        Date d = getDate();
        Calendar codeDate = Calendar.getInstance();
        codeDate.setTime(d);
        int codeYear = codeDate.get(Calendar.YEAR);
        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        if (codeYear > nowYear && codeYear < nowYear-1) {
            throw BarCodePayException.ERROR_BARCODE;
        }
    }

    public Date getDate() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        String dateValue = (year / 10) + getValue().substring(2, 5);
        return DateUtil.string2Date(dateValue, "yyyyMM");
    }
}
